(function($){
    var newsletterData = {};
    var onToolbar = false;
    var selectedBucket = "1";
    var counter = 0;
    var draggedElement = null;
    var connectedEditor = null;

    $.fn.extend({
        newsletterLayout : function(options, arg) {
            if (typeof(options) == "object") {
                options = $.extend({}, $.newsletterLayout.defaults, options);
            }
            this.each(function() {
                for (var fld in options) {
                    jQuery(this).attr("plugin_newsletterLayout_" + fld, options[fld]);
                }
                new $.newsletterLayout(this, options, arg);
            });
            return;
        }
    });

    $.newsletterLayout = function(item, options, arg) {
        if (typeof(options) == "string") {
            var methodName = options;
            options = {};
            for (var fld in $.newsletterLayout.defaults) {
                options[fld] = jQuery(item).attr("plugin_newsletterLayout_" + fld);
            }
            // methods
        } else {
            _constructorCode(item, options, arg);
        }

        $.newsletterLayout.defaults = {
            connectedEditor : null
        }
    }

    var _constructorCode = function(item, options, arg) {
        window.getNewsletterLayoutData = function() {
            return newsletterData;
        }
        counter = jQuery(item).find("td").size() + 1;
        if (options.connectedEditor != null) {
            connectedEditor = options.connectedEditor;
            var editorId = options.connectedEditor.attr("id");
            window[editorId + "_changed"] = function(content) {
                connectedEditorChanged(content);
            }
        }
        var myId = item.id;
        var container = jQuery(item).parents("div").first();
        container.append(jQuery("<button>")
            .attr("id", myId + "_add")
            .text("Add row")
            .click(function() { addRow(item); })
        );
        jQuery(item).find("td").each(function(ndx, elem) {
            applyLayoutCellEvents(elem);
            applyLayoutCellTools(elem);
            applyContentDivTools(elem);
        });
    }

    var connectedEditorChanged = function(content) {
        newsletterData["content_" + selectedBucket] = content;
        if (jQuery("td[id='" + selectedBucket + "'] div.nl_content img.draggable").size() == 0) {
            jQuery("td[id='" + selectedBucket + "'] div.nl_content").append(jQuery("<img>")
                .attr("src", "site/resources/img/document.png")
                .attr("id", selectedBucket + "_dragger")
                .addClass("draggable")
                .mouseover(function() { onToolbar = true; })
            );
            jQuery("td[id='" + selectedBucket + "'] div.nl_content img.draggable").draggable({
                revert : "invalid",
                start : function(event, ui) {
                    draggedElement = this;
                }
            });
        }
    }

    var removeClicked = function(item) {
        if (!confirm("Are you sure that you want to delete this section?")) { return; }
        var cell = jQuery(item).parents("td").first();
        if (cell.find("img.draggable").size() > 0) {
            newsletterData["content_" + cell.attr("id")] = undefined;
            cell.find("img.draggable").remove();
            refreshConnectedEditor();
        }
    }

    var editClicked = function(item) {
        jQuery("td.selected").removeClass("selected");
        var cell = jQuery(item).parents("td").first();
        cell.addClass("selected");
        selectedBucket = cell.attr("id");
        refreshConnectedEditor();
    }

    var refreshConnectedEditor = function() {
        if (connectedEditor != null) {
            connectedEditor.html(
                newsletterData["content_" + selectedBucket] ? newsletterData["content_" + selectedBucket] : ""
            );
        }
    }

    var applyContentDivTools = function(item) {
        jQuery(item).find("div.nl_content").droppable({
            activeClass: "ui-state-hover",
            hoverClass : "ui-state-active",
            drop : function() {
                var id = jQuery(this).parents("td").first().attr("id");
                var oldId = draggedElement.id.split("_")[0];
                var tmp = newsletterData["content_" + oldId];
                draggedElement.id = id + "_dragger";
                newsletterData["content_" +oldId] = newsletterData["content_" + id];
                newsletterData["content_" + id] = tmp;
                if (jQuery(this).find("img.draggable").size() > 0) {
                    jQuery(this).find("img.draggable")
                        .appendTo(jQuery("td[id='" + oldId + "'] div.nl_content"))
                        .attr("id", oldId + "_dragger")
                    ;
                    jQuery("img#" + id + "_dragger")
                        .appendTo(jQuery("td[id='" + id + "'] div.nl_content"))
                        .css({
                            top : 5,
                            left : 10
                        })
                    ;
                } else {
                    jQuery("img#" + id + "_dragger")
                        .appendTo(jQuery("td[id='" + id + "'] div.nl_content"))
                        .css({
                            top : 5,
                            left : 10
                        })
                    ;
                }
                refreshConnectedEditor();
            }
        });
    }

    var applyLayoutCellTools = function(item) {
        jQuery(item).children("div").first().append(jQuery("<div>")
            .addClass("nl_toolbar")
            .append(jQuery("<img>")
                .attr("src", "site/resources/img/icons/database_edit.png")
                .click(function() { editClicked(this); })
            ).append(jQuery("<img>")
                .attr("src", "site/resources/img/icons/database_delete.png")
                .click(function() { removeClicked(this); })
            )
        );
    }

    var applyLayoutCellEvents = function(item) {
/*
        jQuery(item)
            .mouseover(function() {
                jQuery(this).find("div.nl_toolbar").show("fade", {}, 300);
            })
            .mouseout(function() {
                var that = this;
                setTimeout(function() {
                    if (!onToolbar) {
                        jQuery(that).find("div.nl_toolbar").hide("fade", {}, 300);
                    }
                }, 100);
            })
        ;
*/
    }

    var addRow = function(item) {
        var newRow = item.insertRow(-1);
        var leftCell = newRow.insertCell(0);
        var rightCell = newRow.insertCell(1);
        leftCell.id = "" + counter;
        counter++;
        rightCell.id = "" + counter;
        counter++;
        jQuery(leftCell).append(jQuery("<div>")
            .addClass("nl_content")
            .css({
                position : "relative"
            })
        );
        jQuery(rightCell).append(jQuery("<div>")
            .addClass("nl_content")
            .css({
                position : "relative"
            })
        );
        applyLayoutCellTools(leftCell);
        applyLayoutCellTools(rightCell);
        applyLayoutCellEvents(leftCell);
        applyLayoutCellEvents(rightCell);
        applyContentDivTools(leftCell);
        applyContentDivTools(rightCell);
    }

})(jQuery);
